import api from '../../api/index'
import cookies from 'js-cookie'
import store from 'store'
import { Toast } from 'vant'

export default {
  namespaced: true,
  state: {
    token: '',
    userInfo: store.get('userInfo'),
    loading: false,
    showLoginPop: false,
    isValidLogin: false
  },
  mutations: {
    setUserInfo(state, data) {
      state.userInfo = data
      console.log('setUserInfo', state.userInfo)
      store.set('userInfo', data)
    },
    setToken(state, data) {
      state.token = data
      cookies.set('token', data)
    }
  },
  actions: {
    /**
     * 检查当前用户是否登录
     * @param {*} param0
     * @param {*} param1
     */
    async checkLoginState({ commit }, { success }) {
      let res = await api.checkLogin()
      if (!res) return
      if (!res.success) return
      if (res.data.status === 1) {
        success && success()
      }
    },

    /**
     * 获取用户信息
     * @param {*} param0
     */
    async getUserInfo({ commit }, payload) {
      try {
        let ret = await api.getUserInfo()
        if (+ret.retCode === 0) {
          commit('setUserInfo', ret.data)
          if (payload && payload.callback) {
            payload.callback(ret.data)
          }
        } else {
          commit('setUserInfo', null)
        }
      } catch (error) {
        commit('setUserInfo', null)
      }
    },

    /**
     * 用户登录
     * @param {*} param0 email 账户名
     * @param {*} param1 password 登录密码
     * @param { Function } param2 登录成功后回调 onSuccess
     */
    async login({ commit }, { email, password, onSuccess }) {
      this.loading = true
      try {
        let ret = await api.login({ email, password })
        if (+ret.retCode === 0) {
          commit('setToken', ret.data.token)
          commit('setUserInfo', ret.data)
          onSuccess && onSuccess(ret.data)
        } else {
          throw ret.errMsg
        }
      } catch (error) {
        Toast(error.toString())
      }
      this.loading = false
    },

    /**
     * 用户注册
     * @param {*} param0 email 账户名
     * @param {*} param1 password 登录密码
     */
    async register({ commit }, { email, password, code, onSuccess }) {
      if (this.loading) {
        return
      }
      this.loading = true
      try {
        let ret = await api.register({ email, password, code })
        if (+ret.retCode === 0) {
          commit('setToken', ret.data.token)
          commit('setUserInfo', ret.data)
          onSuccess && onSuccess()
        } else {
          throw ret.errMsg
        }
      } catch (error) {
        Toast(error.toString())
      }
      this.loading = false
    },

    // 登录判断
    loginFilter({ commit, state, dispatch }, { onLogin }) {
      if (state.isValidLogin) {
        onLogin && onLogin()
      } else {
        dispatch('showLoginPop')
      }
    }
  }
}
